import React, { createContext, useContext, useState, ReactNode } from 'react';
import { menuData } from '@/data/menuData';

// 系统定义
interface System {
  id: string;
  name: string;
  code: string;
  description: string;
  icon: string;
  color: string;
  menus: MenuItem[];
}

// 菜单项定义
interface MenuItem {
  id: string;
  label: string;
  path: string;
  icon: string;
  children?: MenuItem[];
}

// 系统管理上下文类型
interface SystemContextType {
  currentSystem: System;
  systems: System[];
  switchSystem: (systemId: string) => void;
  systemManagementMenus: MenuItem[];
  helpCenterMenus: MenuItem[];
}

// 创建上下文
const SystemContext = createContext<SystemContextType | undefined>(undefined);

// 系统数据（只包含系统基本信息，菜单从菜单管理页面读取）
const systemsData: System[] = [
  {
    id: 'devops',
    name: 'DevOps系统',
    code: 'DEVOPS',
    description: 'DevOps项目管理与协作平台',
    icon: 'fa-rocket',
    color: 'text-blue-600',
    menus: [] // 菜单将从菜单管理页面动态读取
  },
  {
    id: 'performance',
    name: '绩效管理系统',
    code: 'PERFORMANCE',
    description: '员工绩效评估与考核管理平台',
    icon: 'fa-chart-line',
    color: 'text-green-600',
    menus: [] // 菜单将从菜单管理页面动态读取
  }
];

// 从菜单管理页面获取系统管理菜单的函数
const getSystemManagementMenus = (): MenuItem[] => {
  const systemMenu = menuData.find(menu => menu.id === 'system');
  if (!systemMenu || !systemMenu.children) return [];

  return systemMenu.children.map(child => ({
    id: child.id.toString(),
    label: child.name,
    path: child.path,
    icon: child.icon
  }));
};

// 从菜单管理页面获取帮助中心菜单的函数
const getHelpCenterMenus = (): MenuItem[] => {
  const helpMenu = menuData.find(menu => menu.id === 'help');
  if (!helpMenu || !helpMenu.children) return [];

  // 过滤出需要在侧边栏显示的菜单项（showInSidebar为true或未定义）
  return helpMenu.children
    .filter(child => child.showInSidebar !== false) // 只显示showInSidebar不为false的菜单
    .map(child => ({
      id: child.id.toString(),
      label: child.name,
      path: child.path,
      icon: child.icon
    }));
};

// 从菜单管理页面数据结构中获取菜单的函数
const getMenusFromMenuData = (systemId: string): MenuItem[] => {
  const systemMenu = menuData.find(menu => menu.id === systemId);
  if (!systemMenu || !systemMenu.children) return [];

  // 将菜单管理页面的数据结构转换为Sidebar需要的MenuItem格式
  return systemMenu.children.map(child => ({
    id: child.id.toString(),
    label: child.name,
    path: child.path,
    icon: child.icon
  }));
};

// 提供者组件
interface SystemProviderProps {
  children: ReactNode;
}

export const SystemProvider: React.FC<SystemProviderProps> = ({ children }) => {
  // 在组件内部获取菜单数据，避免模块初始化时的循环依赖
  const systemManagementMenus = getSystemManagementMenus();
  const helpCenterMenus = getHelpCenterMenus();

  const [currentSystem, setCurrentSystem] = useState<System>({
    ...systemsData[0],
    menus: getMenusFromMenuData(systemsData[0].id)
  });

  const switchSystem = (systemId: string) => {
    const system = systemsData.find(s => s.id === systemId);
    if (system) {
      setCurrentSystem({
        ...system,
        menus: getMenusFromMenuData(systemId)
      });
    }
  };

  const value: SystemContextType = {
    currentSystem,
    systems: systemsData,
    switchSystem,
    systemManagementMenus,
    helpCenterMenus
  };

  return (
    <SystemContext.Provider value={value}>
      {children}
    </SystemContext.Provider>
  );
};

// 自定义Hook
export const useSystem = () => {
  const context = useContext(SystemContext);
  if (context === undefined) {
    throw new Error('useSystem must be used within a SystemProvider');
  }
  return context;
};

// 导出类型和常量
export type { System, MenuItem };
export { systemsData };